package com.hernie.piggymall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hernie.common.exception.NoStockException;
import com.hernie.common.to.mq.OrderTo;
import com.hernie.common.to.mq.StockDetailTo;
import com.hernie.common.to.mq.StockLockedTo;
import com.hernie.common.utils.R;
import com.hernie.piggymall.ware.entity.WareOrderTaskDetailEntity;
import com.hernie.piggymall.ware.entity.WareOrderTaskEntity;
import com.hernie.piggymall.ware.feign.OrderFeignService;
import com.hernie.piggymall.ware.feign.ProductFeignService;
import com.hernie.common.to.SkuHasStockVo;
import com.hernie.piggymall.ware.service.WareOrderTaskDetailService;
import com.hernie.piggymall.ware.service.WareOrderTaskService;
import com.hernie.piggymall.ware.vo.OrderItemVo;
import com.hernie.piggymall.ware.vo.OrderVo;
import com.hernie.piggymall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hernie.common.utils.PageUtils;
import com.hernie.common.utils.Query;

import com.hernie.piggymall.ware.dao.WareSkuDao;
import com.hernie.piggymall.ware.entity.WareSkuEntity;
import com.hernie.piggymall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private OrderFeignService orderFeignService;


    /**
     * 解锁库存
     *
     * @param skuId
     * @param wareId
     * @param num
     * @param taskDetailId
     */
    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        // 库存解锁
        this.baseMapper.unlockStock(skuId, wareId, num);
        // 更新库存工作单状态
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(taskDetailId);
        detailEntity.setLockStatus(2);   // 变为已解锁
        wareOrderTaskDetailService.updateById(detailEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<WareSkuEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank((String) params.get("skuId"))) {
            queryWrapper.eq(WareSkuEntity::getSkuId, params.get("skuId"));
        }
        if (StringUtils.isNotBlank((String) params.get("wareId"))) {
            queryWrapper.eq(WareSkuEntity::getWareId, params.get("wareId"));
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(WareSkuEntity wareSkuEntity) {
        // 判断数据库中是否存在这个库存记录
        LambdaQueryWrapper<WareSkuEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WareSkuEntity::getSkuId, wareSkuEntity.getSkuId()).eq(WareSkuEntity::getWareId, wareSkuEntity.getWareId());
        WareSkuEntity entity = this.baseMapper.selectOne(wrapper);
        if (entity == null) {
            wareSkuEntity.setStockLocked(0);
            // 远程查询sku名字
            try {
                R info = productFeignService.info(wareSkuEntity.getSkuId());
                Map<String, Object> data = (Map<String, Object>) info.get("data");
                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
            this.baseMapper.insert(wareSkuEntity);
        } else {
            wareSkuEntity.setStock(entity.getStock() + wareSkuEntity.getStock());
            this.baseMapper.update(wareSkuEntity, wrapper);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        // 查询当前sku的总库存量
        return skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            Long count = this.baseMapper.getSkuStock(skuId);
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count != null && count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
//                this.listByIds(skuIds).stream().map(sku -> {
//            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
//            skuHasStockVo.setSkuId(sku.getSkuId());
//            skuHasStockVo.setHasStock(sku.getStock() > 0);
//            return skuHasStockVo;
//        }).collect(Collectors.toList());
    }

    /**
     * 为某个订单锁定库存
     * <p>
     * Transactional 默认只要是运行时异常都会回滚
     * <p>
     * 库存解锁场景：
     * 1）、下订单成功，订单过期没有支付被系统自动取消、被用户手动取消，都要解锁库存
     * 2）、下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。
     * 之前锁定的库存就要自动解锁
     *
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单的详情
         * 方便追溯
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        // 找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            // 查询这个商品在哪里有库存
            List<Long> wareIds = this.baseMapper.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        // 锁定库存
        Boolean allLock = true;
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                // 没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                // 成功返回1，否则返回0
                Long count = this.baseMapper.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    skuStocked = true;
                    // 告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(taskDetailEntity);
                    // 如果每一个商品都锁定成功，将当前商品锁定了几件的工作单记录发送给MQ
                    // 如果锁定失败。前面保存的工作单信息就回滚了，对已经发出去的消息，即使要解锁记录，由于数据库查询不到id，所以就不用解锁
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, detailTo);
                    lockedTo.setDetail(detailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.lock", lockedTo);
                    break;
                } else {
                    // 当前仓库锁定失败，重试下一个仓库
                }
            }
            if (skuStocked == false) {
                // 当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }
        // 到达这一步代表所有商品的库存都锁定成功
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        // 查询数据库关于这个订单的锁定库存信息
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if (byId != null) {
            Long id = to.getId(); // 库存工作单id
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn(); // 订单号
            // 根据订单号查询订单的状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                // 订单数据返回成功
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                if (data == null || data.getStatus() == 4) {
                    if (byId.getLockStatus() == 1) {    // 当前库存工作单详情，状态为1，已锁定但是未解锁才可以解锁
                        // 订单不存在和订单已经被取消，都要解锁库存
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                // 消息拒绝以后重新放入队列中，让订阅者继续消费-解锁
                throw new RuntimeException("远程服务失败");
            }
        } else {
            // 数据库没有该库存锁定信息，无需解锁（库存锁定失败，库存回滚了，这种情况无需解锁）
        }
    }

    // 防止订单服务卡顿，导致订单状态一直处于新建状态，库存消息优先到期，但是订单状态没有改变，库存无法扣减就结束
    // 防止卡顿的订单永远不能解锁库存
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        // 查一下最新的库存状态，防止重复解锁库存
        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        // 按照工作单找到所有 没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new LambdaQueryWrapper<WareOrderTaskDetailEntity>()
                .eq(WareOrderTaskDetailEntity::getTaskId, id)
                .eq(WareOrderTaskDetailEntity::getLockStatus, 1));
        for (WareOrderTaskDetailEntity entity : list) {
            unLockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}